package com.wanxi.dangdang.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanxi.dangdang.common.UserType;
import com.wanxi.dangdang.mapper.UserMapper;
import com.wanxi.dangdang.model.pojo.BUser;
import com.wanxi.dangdang.model.vo.*;
import com.wanxi.dangdang.service.UserService;
import com.wanxi.dangdang.service.redis.RedisService;
import com.wanxi.dangdang.util.DrawCheck;
import com.wanxi.dangdang.util.JwtTokenUtil;
import com.wanxi.dangdang.util.PasswordUtil;
import com.wanxi.dangdang.util.SmsToPhone;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private SmsToPhone smsToPhone;
    @Autowired
    private RedisService redisService;

    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Override
    public BUser findById(Long id) {
        BUser byId = userMapper.findById(id);

        return byId;
    }

    @Override
    public PageInfo<BUser> findPage(BUserPageVo bUserPageVo) {
        PageHelper.startPage(bUserPageVo.getPageNum(),bUserPageVo.getPageSize());
        List<BUser> all = userMapper.findAll(bUserPageVo);
        PageInfo<BUser> pageInfo = new PageInfo<>(all);
        return pageInfo;
    }

    @Override
    public void repassword(Long id) {
        BUser bUser = new BUser();
        bUser.setId(id);
        bUser.setUpdateTime(new Date());
        String password = PasswordUtil.randomPassword();
        System.out.println("============================================================================================================");
        System.out.println(password);
        System.out.println("============================================================================================================");
        String encode = passwordEncoder.encode("123456");
        bUser.setPassword(encode);
        userMapper.updatePassById(bUser);
    }

    @Override
    public Long add(BUserAddVo bUserAddVo) {
        Date date = new Date();
        BUser bUser = new BUser();
        BeanUtils.copyProperties(bUserAddVo,bUser);
        bUser.setPassword(passwordEncoder.encode(bUserAddVo.getPassword()));
        bUser.setCreateTime(date);
        bUser.setUpdateTime(date);
        if (StringUtils.isBlank(bUser.getUserType())){
        bUser.setUserType("0");}

        if (StringUtils.isBlank(bUser.getHeadPicture())){
            bUser.setHeadPicture("/headerPic/head01.png");
        }
        userMapper.add(bUser);
        return bUser.getId();
    }

    @Override
    public void updateById(BUserUpdateVo bUserUpdateVo) {
        BUser bUser = new BUser();
        BeanUtils.copyProperties(bUserUpdateVo,bUser);
        userMapper.updateAllById(bUser);
    }

    @Override
    public void deleteById(Long id) {
        BUser bUser = new BUser();
        bUser.setId(id);
        bUser.setUpdateTime(new Date());
        bUser.setDeleteStatus(1);
        userMapper.deleteById(bUser);
    }

    @Override
    public HashMap<String,String> loginByCode(LoginVo loginVo) {
        BUser bUser = userMapper.findByAccount(loginVo.getAccount());
        HashMap<String, String> map = new HashMap<>();
        if (ObjectUtils.isEmpty(bUser)){
            return map;
        }
        //从redis里面拿去 phone Code ，名称为 电话号码 + 发送日期 时分秒
        String token = jwtTokenUtil.generateToken(bUser.getPhone(), bUser.getId(), UserType.BUSER);
        map.put("token",tokenHead + " " + token);
        map.put("tokenHeader",tokenHeader);
//        map.put("BUserId",bUser.getId().toString());
        return map;
    }

    @Override
    public HashMap<String,String> loginByPass(LoginVo loginVo) {
        BUser bUser = userMapper.findByAccount(loginVo.getAccount());
        boolean matches = passwordEncoder.matches(loginVo.getPassword(), bUser.getPassword());
        HashMap<String, String> map = new HashMap<>();
        String token = null;
        if (matches){
            token = jwtTokenUtil.generateToken(bUser.getPhone(), bUser.getId(), UserType.BUSER);
        }else{
            return map;
        }
        map.put("token",tokenHead + " " + token);
        map.put("tokenHeader",tokenHeader);
//        map.put("BUserId",bUser.getId().toString());
        return map;
    }

    @Override
    public void getPhoneCode(String phone) throws Exception {
        //生成随机的数字
        int code = (int)(Math.random() * 10000);
        //放置在redis里
                redisService.set("codeTel-"+phone,1234+"",300);
//        smsToPhone.createClient(phone,code);
    }

    @Override
    public Map<String,String> getPictureCode() throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        DrawCheck drawCheck = new DrawCheck();

        //1.在内存中创建一张图片
        BufferedImage bi = new BufferedImage(120, 30,BufferedImage.TYPE_INT_RGB);
        //2.得到图片
        Graphics g = bi.getGraphics();
        //3.设置图片的背影色
        drawCheck.setBackGround(g);
        //4.设置图片的边框
        drawCheck.setBorder(g);
        //5.在图片上画干扰线
        drawCheck.drawRandomLine(g);
        //6.写在图片上随机数
        String random =  drawCheck.drawRandomNum((Graphics2D) g);//生成中文验证码图片

        //7.将随机数存在redis中
        Random randomNum = new Random(new Date().getTime());
        int length = randomNum.nextInt(3)+3;
        String num = Long.toString(System.currentTimeMillis()).substring(length);
        //放置在redis里
        redisService.set("codePicId-"+num,random,300);

        //10.将图片写给浏览器
        ImageIO.write(bi, "jpg", output);

        byte[] captcha = output.toByteArray();
        BASE64Encoder encoder = new BASE64Encoder();
        String imagestr =  encoder.encode(captcha);
        HashMap<String, String> map = new HashMap<>();
        map.put("codePic",imagestr);
        map.put("pic_id",num);
        return map;
    }


    @Override
    public BUserCheckVo checkAccount(String account) {
        return userMapper.checkAccount(account);
    }
}
